# -*- coding: utf-8 -*-
# @Author  : longbhu
# @Time    : 2025/3/17 14:52
# @Function:
"""
根据一个输入的 FVC_2022_250m.tif 文件，数组每个数代表FVC，根据图中公式得到C。将C数据保存成跟输入文件一样参数的tif文件
    mask_zero = (fvc == 0)
    mask_nonzero = (fvc > 0) & (fvc <= 0.783)
    mask_large = (fvc > 0.783)
"""

import numpy as np
import rasterio

from calc_v1.DataPreparationProgram import process_tif_file_thread


# from math import log10


def calculate_C(fvc):
    """
    根据FVC值计算C值。
    """
    c = np.zeros_like(fvc, dtype=np.float32)

    mask_zero = (fvc == 0)
    mask_nonzero = (fvc > 0) & (fvc <= 0.783)
    mask_large = (fvc > 0.783)

    c[mask_zero] = 1
    c[mask_nonzero] = 0.6508 - 0.3436 * np.log10(fvc[mask_nonzero])
    c[mask_large] = 0

    return c


def process_fvc_tif(input_path, output_path):
    """
    处理FVC TIFF文件，计算C值并保存为新的TIFF文件。
    """
    with rasterio.open(input_path) as src:
        # 读取FVC数据和元数据
        fvc = src.read(1).astype(np.float32)
        meta = src.meta.copy()

        # 计算C值
        c = calculate_C(fvc)

        # 更新元数据以匹配新数据类型
        meta.update(dtype=c.dtype)

        # 写入新的TIFF文件
        with rasterio.open(output_path, 'w', **meta) as dst:
            dst.write(c, 1)


# 示例调用
input_file = r"G:\GEP_data\input\sr\FVC_2022_250m.tif"
output_file = r"G:\GEP_data\input\sr\C_2022_250m.tif"
# process_fvc_tif(input_file, output_file)


# 插值et到30m
# todo 统一做插值

# input_tif_path = r'G:\GEP_data\input\wr\era5_download\et\et_total_day_annual_sum.tif'
process_tif_file_thread(output_file, 2)